<template>
  <el-dialog :title="type === 'add' ? '新增用户' : '编辑用户'" :visible.sync="centerDialogVisible" width="700px">
    <el-form
      ref="form"
      :rules="rules"
      :model="ruleform"
      label-width="80px"
      label-position="left"
      class="form"
      :inline="true"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleform.username" />
      </el-form-item>
      <el-form-item label="账号" style="margin-left:20px;" prop="account">
        <el-input v-model="ruleform.account" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="ruleform.phone" />
      </el-form-item>
      <el-form-item label="密码" style="margin-left: 20px;" prop="password">
        <el-input v-model="ruleform.password" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="confirm">确 定</el-button>
      <el-button @click="centerDialogVisible = false">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'EditOrAdd',
  emits: ['submit'],
  props: {
    type: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      centerDialogVisible: false, // 弹框显示
      ruleform: {
        username: '',
        phone: '',
        account: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'change' }],
        phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '请输入正确格式手机号', trigger: 'change' }],
        account: [{ required: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'change' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12个字符', trigger: 'change' }]
      }
    }
  },
  methods: {
    // 提交
    confirm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.$message({
            type: 'success',
            message: (this.type === 'add' ? '新增' : '编辑') + '用户成功'
          })
          this.$emit('submit', { ...this.ruleform })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  .form {
    margin: 0px 20px;
  }

  .dialog-footer {
    margin-top: 10px;
  }
}
</style>
